﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


namespace MultiDAQ_Analysis.Util
{
    public class UdpMessenger
    {
        private UdpClient client;
        private IPEndPoint listenEP;
        private IPEndPoint remoteEP;
        private Thread listenThread;
        private bool isRunning;

        public event Action<string> OnMessageReceived;

        public void Start()
        {
            listenEP = new IPEndPoint(IPAddress.Any, AppConfig.UdpListenPort);
            remoteEP = new IPEndPoint(AppConfig.UdpRemoteIP, AppConfig.UdpRemotePort);

            client = new UdpClient(listenEP);
            isRunning = true;

            listenThread = new Thread(() =>
            {
                while (isRunning)
                {
                    try
                    {
                        var recvEP = new IPEndPoint(IPAddress.Any, 0);
                        var data = client.Receive(ref recvEP);
                        string message = Encoding.UTF8.GetString(data);
                        OnMessageReceived?.Invoke(message);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("UDP 接收错误: " + ex.Message);
                    }
                }
            });

            listenThread.IsBackground = true;
            listenThread.Start();
        }

        public void Send(string message)
        {
            if (string.IsNullOrWhiteSpace(message)) return;

            var data = Encoding.UTF8.GetBytes(message);
            client?.Send(data, data.Length, remoteEP);
        }

        public void Stop()
        {
            isRunning = false;
            try { client?.Close(); } catch { }
            try { listenThread?.Abort(); } catch { }
        }
    }
}
